package app.base.commons;

import java.io.StringWriter;

import java.sql.ResultSet;

import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import app.base.modules.Module;

public class Tools {

	//Map<String, Object> params: 传入到所有hook的模块
	public static String hookExecModule(String hookName, Map<String, Object> params) throws Throwable {
		
		String sql = "select a.module_classpath " +
						"from sys_modules a, sys_hooks b, sys_hook_module c " +
						"where b.hook_name = '" + hookName + "' " + 
							"and b.hook_id = c.hook_id " +
							"and c.module_id = a.module_id " +
							"and a.module_state = '0' " +
						"order by c.hook_position asc";
		
		Db db = null;
		
		StringBuffer sb = new StringBuffer("");
		
		try{    
	   		db = Db.getInstance(Constants.DB_CONTEXT_LOOKUP_NAME);
	   							
			ResultSet rs = db.executeQuery(sql);
		   
			while(rs.next()){    
				sb.append(loadModule(rs.getString(1).trim(), params));
			}
		    			
			rs.close();	   
		}    
		catch(Throwable t){    
		    t.printStackTrace();    
		}    
		finally {
			db.release();
		}
		
		return sb.toString();
	}
	
	//动态加载模块类
	public static String loadModule(String moduleClassPath, Map<String, Object> params) throws Throwable {
		
		Module m = (Module) Class.forName(moduleClassPath).newInstance();

		return m.getWebPageBlockContent(params);
	}
	
	//调用Velocity进行模板转换
	public static String velocityTranslate(
			String velocityPropsFileName, 
			VelocityContext context,
			String templateFileName
	) throws Throwable {
		
		Velocity.init(velocityPropsFileName); 
		
		Template template = Velocity.getTemplate(templateFileName);
		      
		StringWriter writer = new StringWriter();
		
		template.merge(context, writer);
		
		return writer.toString();
	}
}
